package com.example.dps;



import com.google.gson.JsonObject;
import com.loopj.android.http.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 
 * @author merrickc
 * 
 * contains useful functions for sending info and querying the web server. (ie Logins, registration)
 *
 */
public class WebHelper {
	
	
	Object mLock = new Object();
	
	Context activity;
	
	String tag = "WebServer";
	
	
	public static final String DOMAIN = "downpaymentsaver.com";
	
	static String DPSSERVER = "https://" + DOMAIN + "/downpaymentserver/";
	
	
	DBHelper dbHelper;
	
	AccountDBHelper accountDBHelper;
	
	HashMap bankMap = new HashMap();
	
	String errorMessage = "";
	
	
	
	public HttpContext httpContext;
	public static PersistentCookieStore cookieStore;
	

	ProgressDialog progressDialog;
	
	List<Cookie> cookies = null;
	
	
	/**
	 * should the user stay logged in?
	 * value passed by webHelper.login function
	 */
	boolean rememberUser = false;
	
	
	public WebHelper(Context context){
		
		
		bankMap.put("Capital One 360", 4723);
		bankMap.put("Bank of America", 2931);
		//bankMap.put("Citi Bank", 1644); has MFA
		//bankMap.put("TD Bank", 9210);	has MFA
		bankMap.put("Chase Bank", 663);
		bankMap.put("HSBC", 3830);
		bankMap.put("Wachovia", 2022);
		bankMap.put("South Trust", 3514);
		bankMap.put("Capital One", 15800);
		bankMap.put("Comerica", 4330);
		//bankMap.put("DagBank", 11195);
		//bankMap.put("Dag QA", 14748);
		bankMap.put("M&T Bank", 3309);
		bankMap.put("WSFS", 12144);
		
		
		
		this.activity = context;
		
		this.dbHelper = new DBHelper(context);
		
		this.accountDBHelper = new AccountDBHelper(context);
		
		cookieStore = new PersistentCookieStore(this.activity);
		//client.setCookieStore(cookieStore);
		
		
		        
	}
	
	
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = null;
		LayoutInflater inflater = null;
		
		switch (id) {
		case Constants.ERROR_DIALOG:
			
			builder = new AlertDialog.Builder(this.activity);
		    // Get the layout inflater

		    // Inflate and set the layout for the dialog
		    // Pass null as the parent view because its going in the dialog layout
			builder.setMessage(this.errorMessage);
		    return builder.create();
			
			
			
			
			
			
		}
		
		return null;
	}
	
	public class getTransfersTask extends AsyncTask<Void, Integer, String>{
		
		Context activity;
		
		getTransfersTask(Context activity2){
			this.activity=activity2;
		}

		@Override
		protected String doInBackground(Void... params) {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "getTransfers.php");
	        
	        
	        // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				
				JSONObject jsonObject = null;
				
				try {
					jsonObject = new JSONObject(result);

					
					return result;
					
					
				} catch (JSONException e) {
					// 
					e.printStackTrace();
				}

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		public void onPostExecute(String result){
			
			if(this.activity instanceof ViewSavingsActivity){
				((ViewSavingsActivity) this.activity).onGetTransfers(result);
			}
			
			
		}
		
		
	}
	
	public class performTransferTask extends AsyncTask<Integer, Integer, Boolean>{

		
		Context activity;
		
		performTransferTask(Context activity2){
			this.activity = activity2;
		}
		
		@Override
		protected Boolean doInBackground(Integer... params) {
			
			int fromAccountID = params[0];
			int toAccountID = params[1];
			int amount = params[2];
			
			JSONObject json = new JSONObject();
			
			
			try {
				
				json.put("fromAccountID", fromAccountID);
				json.put("toAccountID", toAccountID);
				json.put("amount", amount);
				
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "performTransfer.php");
		    
		    List<NameValuePair> values = new ArrayList<NameValuePair>();
	        values.add(new BasicNameValuePair("json", json.toString()));

	        // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(values));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				
				JSONObject jsonObject = null;
				
				try {
					jsonObject = new JSONObject(result);
					result = jsonObject.getString("status");

					
					if(result.equals("success")) return true;
					
					
				} catch (JSONException e) {
					
					e.printStackTrace();
				}

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return false;
		}
		
		@Override
		public void onPostExecute(Boolean result){
			
			super.onPostExecute(result);
			
			if(this.activity instanceof ConfirmTransferActivity){
				((ConfirmTransferActivity) this.activity).onPerformTransfer();
			}
			
			

		}
		

		
	}
	
	
	public class checkSessionTask extends AsyncTask<String, Integer, Boolean>{
		
		Context activity;
		
		checkSessionTask(Context activity){
			this.activity=activity;
		}

		@Override
		protected Boolean doInBackground(String... usernames) {
			
			String username = usernames[0];
			
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("username", username));
	        
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/checkSession.php");
		    
		    try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		    
		    
		    boolean sessionOpen = false;
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    


	        try {
	        	
				HttpResponse response = httpclient.execute(httppost, httpContext);
				
				//saveCookies();
				
				String result = EntityUtils.toString(response.getEntity());


				JSONObject jsonObject = null;
				
				try {
					jsonObject = new JSONObject(result);
					
					result = jsonObject.getString("status");
					
					if(result.equals("success")){
						sessionOpen = true;
						return sessionOpen;
					}
					else{
						sessionOpen = false;
						return sessionOpen;
					}
					
				} catch (JSONException e1) {
					
					e1.printStackTrace();
				}
				

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

	       return sessionOpen;
				
		}
		
		
		@Override
		public void onPostExecute(Boolean result){
			
			if(result == true){
				//user is logged in. return success
				
			}
			else{
				//user is not logged in, return false. go to log in
				
				Intent intent = new Intent(activity, LoginActivity.class);
				intent.putExtra("START_TAB", "add_money");
				this.activity.startActivity(intent);
				
			}
			
		}
		
		
	}
	
	
	public class getUserInfoTask extends AsyncTask<Integer, String, JSONObject>{

		DBHelper dbHelper;
		
		AccountDBHelper accountDBHelper;
		
		ProgressDialog dialog;
		
		Context context;
		
		boolean showDialog = false;
		
		getUserInfoTask(Context context, Boolean showDialog){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			
			this.showDialog = showDialog;
			
			this.accountDBHelper = new AccountDBHelper(context);
			this.dbHelper = new DBHelper(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			if(showDialog == true)
				dialog = ProgressDialog.show(context,"", "Retrieving Search Results");
			
		}
		@Override
		protected JSONObject doInBackground(Integer... userids) {
			
			

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "getUserInfo.php");
		    

		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				try {
					
					
					/** make sure the account table is empty **/
					//this.accountDBHelper.deleteAll();

					JSONObject jsonObject = new JSONObject(result);
					

					
					return jsonObject;
						
					
				} catch (JSONException e) {
					
					e.printStackTrace();
					return null;
				}

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;

		}

		
		@Override
		public void onPostExecute(JSONObject json){
			
			super.onPostExecute(json);
			
			if(activity instanceof ViewSavingsActivity){
				((ViewSavingsActivity) activity).onGetUserInfo(json);
			}
			
			if(activity instanceof TabRoot){
				((TabRoot) activity).onGetUserInfo(json);
			}
			
			if(activity instanceof MainActivity){
				((MainActivity) activity).onGetUserInfo(json);
			}
			
			
			if(activity instanceof AddMoneyActivity){
				//((AddMoneyActivity) activity).onGetUserInfo(accounts);
			}
			if(activity instanceof ConfirmTransferActivity){
				//((ConfirmTransferActivity) activity).onGetUserInfo(accounts);
			}
			

			try{
		        if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
			}
			catch(Exception e){
				//nothing to do here;
			}

			
		}
		
		
	}
	
	/** sends updated user info to the server **/
	public class updateUserInfoTask extends AsyncTask<JSONObject, Integer, Boolean>{

		@Override
		protected Boolean doInBackground(JSONObject... objects) {
			
			JSONObject json = objects[0];

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "updateUser.php");
		    
		    List<NameValuePair> values = new ArrayList<NameValuePair>();
	        values.add(new BasicNameValuePair("json", json.toString()));
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(values));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				
				JSONObject jsonObject = null;
				
				try {
					jsonObject = new JSONObject(result);
					result = jsonObject.getString("status");
					//Log.e(tag, result);
					
					if(result.equals("success")) return true;
					
					
				} catch (JSONException e) {
					
					e.printStackTrace();
				}

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return false;
		}
		
		
		
	}
	
	/** sends updated account info to the server **/
	public class updateAccountInfoTask extends AsyncTask<JSONObject, Integer, Boolean>{
		
		ProgressDialog dialog;
			
		Context context;
		
		updateAccountInfoTask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			
		}
			
			

		@Override
		protected Boolean doInBackground(JSONObject... objects) {
			
			JSONObject json = objects[0];

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "updateAccounts.php");
		    
		    List<NameValuePair> values = new ArrayList<NameValuePair>();
	        values.add(new BasicNameValuePair("json", json.toString()));
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(values));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				
				JSONObject jsonObject = null;
				
				try {
					jsonObject = new JSONObject(result);
					result = jsonObject.getString("status");
					
					if(result.equals("success")) return true;
					
					
				} catch (JSONException e) {
					
					e.printStackTrace();
				}

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return false;
		}
		
		@Override
		public void onPostExecute(Boolean result){
			
			super.onPostExecute(result);
			
			//dialog.dismiss();
			if(!result){
				Toast.makeText(this.context, "Failed to log in", Toast.LENGTH_LONG).show();
			}

	        if (dialog.isShowing()) {
	            dialog.dismiss();
	        }
			
		}
		
		
	}

	public class getAccountInfoTask extends AsyncTask<Integer, String, Account[]>{

		DBHelper dbHelper;
		
		AccountDBHelper accountDBHelper;
		
		ProgressDialog dialog;
		
		Context context;
		
		boolean showDialog = false;
		
		getAccountInfoTask(Context context, Boolean showDialog){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			
			this.showDialog = showDialog;
			
			this.accountDBHelper = new AccountDBHelper(context);
			this.dbHelper = new DBHelper(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			if(showDialog == true)
				dialog = ProgressDialog.show(context,"", "Retrieving Account Information");
			
		}
		@Override
		protected Account[] doInBackground(Integer... userids) {
			
			String userid = String.valueOf(userids[0]);
			

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "getAccounts.php");
		    

		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    

		    
	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());
				//Log.e("getAccountINFOTask", result);

				try {
					
					String[] objects = result.split("!!");
					
					/** make sure the account table is empty **/
					this.accountDBHelper.deleteAll();
					
					Account[] accounts = new Account[objects.length];
					int index = 0;
					
					for(String entry : objects){
						
						JSONObject jsonObject = new JSONObject(entry);
						

						//add parsed account to account DBHelper
						
						if(jsonObject.has("status") && jsonObject.getString("status").equals("fail")){
							
							return null;
						}
						
						Account account = new Account(jsonObject);
						
						accounts[index] = account;
						index++;


						
						
						
					}
					
					
					return accounts;
						
					
				} catch (JSONException e) {
					
					e.printStackTrace();
					return null;
				}

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;

		}
		
		@Override
		public void onPostExecute(Account[] accounts){
			
			super.onPostExecute(accounts);
			
			if(activity instanceof ViewSavingsActivity){
				((ViewSavingsActivity) activity).onGetAccountInfo(accounts);
			}
			
			if(activity instanceof AddMoneyActivity){
				((AddMoneyActivity) activity).onGetAccountInfo(accounts);
			}
			if(activity instanceof ConfirmTransferActivity){
				((ConfirmTransferActivity) activity).onGetAccountInfo(accounts);
			}
			

			try{
		        if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
			}
			catch(Exception e){
				//nothing to do here;
			}

			
		}
		
		
	}
	
	
	public class AnswerMFATask extends AsyncTask<JSONObject, String, JSONObject>{

		DBHelper dbHelper;
		
		AccountDBHelper accountDBHelper;
		
		ProgressDialog dialog;
		
		Context context;
		
		AnswerMFATask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			
			this.accountDBHelper = new AccountDBHelper(context);
			this.dbHelper = new DBHelper(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			
			dialog = ProgressDialog.show(context,
	                "", "Retrieving Account Information");
			
		}
		@Override
		protected JSONObject doInBackground(JSONObject... jsons) {
			
			JSONObject json = jsons[0];
			

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/addYodleeAccount.php");
		    
		    List<NameValuePair> values = new ArrayList<NameValuePair>();
	        values.add(new BasicNameValuePair("json", json.toString()));
	        values.add(new BasicNameValuePair("answerMFA", "1"));
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(values));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
	        
	        
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;

		}

		
		@Override
		public void onPostExecute(JSONObject json){
			
			super.onPostExecute(json);
			
			if(activity instanceof ViewSavingsActivity){
				//((ViewSavingsActivity) activity).onGetAccountInfo(json);
			}
			
			if(activity instanceof AddMoneyActivity){
				//((AddMoneyActivity) activity).onGetAccountInfo(accounts);
			}
			
			if(activity instanceof MFAActivity){
				
				
			}
			

			try{
		        if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
			}
			catch(Exception e){
				//nothing to do here;
			}

			
		}
	}
	
	
	public class getExistingAccountInfoTask extends AsyncTask<JSONObject, String, JSONObject>{

		DBHelper dbHelper;
		
		AccountDBHelper accountDBHelper;
		
		ProgressDialog dialog;
		
		Context context;
		
		boolean showDialog;
		
		getExistingAccountInfoTask(Context context, boolean showDialog){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			
			this.showDialog = showDialog;
			
			this.accountDBHelper = new AccountDBHelper(context);
			this.dbHelper = new DBHelper(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			if(showDialog){
				dialog = ProgressDialog.show(context,
		                "", "Retrieving Account Information");
			}
			
			
		}
		@Override
		protected JSONObject doInBackground(JSONObject... json) {
			
			

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/getAccountInfo.php");
		    
		    /**
		    //if arguments are not null, add the json bank info 
		    if(json[0] != null){
		    	List<NameValuePair> values = new ArrayList<NameValuePair>();
		        values.add(new BasicNameValuePair("json", json[0].toString()));
		        
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(values));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		    }
		    **/
		    
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());
				//Log.e(tag, "getAccountInfo RESPONSE");
				Log.e("WEB RESPONSE", result);
				
				try {
					JSONObject jsonResponse = new JSONObject(result);
					return jsonResponse;
				} catch (JSONException e) {
					
					e.printStackTrace();
					return null;
				}

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;

		}
		
		
		@Override
		public void onPostExecute(JSONObject json){
			
			super.onPostExecute(json);
			
			if(json == null) return;
			
			String status = null;
			String message = null;
			
			try {
				status = json.getString("status");
				message = json.getString("message");
			} catch (JSONException e1) {
				//e1.printStackTrace();
			}
			
			
			if(message != null && message.equals("mfa")){
				/** respond to MFA questions **/
				try {
					int count = json.getInt("count");
					
					String[] questions = new String[count];		
					
					for(int i = 0; i < count; i++){
						
						questions[i] = json.getString(String.valueOf(i));

						
					}
					
					
					
				} catch (JSONException e) {
					
					e.printStackTrace();
				}
				
			}
			
			
			if(activity instanceof ViewSavingsActivity){
				((ViewSavingsActivity) activity).onGetExistingAccountInfo(json);

			}
			
			if(activity instanceof AddMoneyActivity){

			}
			if(activity instanceof LinkExistingAccountActivity){

			}
			
			

			try{
		        if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
			}
			catch(Exception e){
				//nothing to do here;
			}

			
		}



		
		
	}
	
	/** adds a bank account to a yodlee ID **/
	public class addExistingAccountInfoTask extends AsyncTask<JSONObject, String, JSONObject>{

		DBHelper dbHelper;
		
		AccountDBHelper accountDBHelper;
		
		ProgressDialog dialog;
		
		Context context;
		
		boolean showDialog;
		
		addExistingAccountInfoTask(Context context, boolean showDialog){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			
			this.showDialog = showDialog;
			
			this.accountDBHelper = new AccountDBHelper(context);
			this.dbHelper = new DBHelper(context);
		}
		
		
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			if(showDialog){
				dialog = ProgressDialog.show(context,
		                "", "Retrieving Account Information");
			}
			
			
		}
		@Override
		protected JSONObject doInBackground(JSONObject... json) {
			
			

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/addYodleeAccount.php");
		    

		    //if arguments are not null, add the json bank info 
		    if(json[0] != null){
		    	List<NameValuePair> values = new ArrayList<NameValuePair>();
		        values.add(new BasicNameValuePair("json", json[0].toString()));
		        
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(values));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		    }

		    
		    
		    
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());
				
				try {
					JSONObject jsonResponse = new JSONObject(result);
					return jsonResponse;
				} catch (JSONException e) {
					
					e.printStackTrace();
					return null;
				}

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;

		}
		
		
		@Override
		public void onPostExecute(JSONObject json){
			
			super.onPostExecute(json);
			
			if(json == null){
				if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
				//return;
			}
			String status = null;
			String message = null;
			
			try {
				status = json.getString("status");
				
			} catch (JSONException e1) {
				e1.printStackTrace();
			} catch(NullPointerException e){
				
			}
			
			
			//if(status.equalsIgnoreCase("success"))
			
			
			if(activity instanceof ViewSavingsActivity){
				//((ViewSavingsActivity) activity).onGetExistingAccountInfo(acount);

			}
			
			if(activity instanceof AddMoneyActivity){
				//((AddMoneyActivity) activity).onGetAccountInfo(accounts);
			}
			if(activity instanceof LinkExistingAccountActivity){
				((LinkExistingAccountActivity)activity).onAddExistingAccountInfo(json);
				
			}
			
			

			try{
		        if (dialog.isShowing()) {
		            dialog.dismiss();
		        }
			}
			catch(Exception e){
				//nothing to do here;
			}

			
		}

	}
	
	
	

	
	public class createAccountTask extends AsyncTask<JSONObject, Integer, Boolean>{

		@Override
		protected Boolean doInBackground(JSONObject... objects) {
			
			JSONObject object = objects[0];
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/createAccount.php");
		    
		    List<NameValuePair> jsonValues = new ArrayList<NameValuePair>();
	        jsonValues.add(new BasicNameValuePair("json", object.toString()));
	        
	        //Log.e("POSTING", object.toString());
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(jsonValues));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());

				try {
					JSONObject jsonObject = new JSONObject(result);
					
					if(jsonObject.getString("status").equals("success")){

						return true;
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return false;

		}
		
		@Override
		protected void onPostExecute(Boolean result){

			if(result == true){
				WebHelper.this.dbHelper.setBoolean(DBHelper.COLUMN_ACCOUNT_CREATED, 1);
			
			
			}
			
		}

	}
	
	
	/**
	 * async task to log in the app user. queries the web server and pops up a progress dialog.
	 * @author merrickc
	 *
	 */
	public class loginTask extends AsyncTask<String, Integer, Boolean> {

		
		ProgressDialog dialog;
		
		Context context;
		
		String username;
		
		loginTask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
			username = null;
		}
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			
			try{
				dialog = ProgressDialog.show(WebHelper.this.activity,
		                "", "Logging in...");
			}
			catch(Exception e){

			}
			
            
            
        }
		
		@Override
		protected Boolean doInBackground(String... params) {
			
			publishProgress(1);
			
			String username = params[0];
			String password = params[1];
			String rememberMe = params[2];
			
			this.username = username; 
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("username", username));
	        nameValuePairs.add(new BasicNameValuePair("password",Utility.md5(password)));
	        nameValuePairs.add(new BasicNameValuePair("rememberMe", rememberMe));
	        
	        
	        
	        HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/login.php");
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				String result = EntityUtils.toString(response.getEntity());
				//Log.e("WebResponse Login", result);
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject(result);
				} catch (JSONException e) {
					
					e.printStackTrace();
				}
				
				//jsonObject.
				try {
					result = jsonObject.getString("status");

				} catch (JSONException e) {
					
					e.printStackTrace();
				}
				
				
				if(result.equals("success")) return true;
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

	        

	        return false;

		}
		
		@Override
		public void onProgressUpdate(Integer... progress){
			this.dialog.incrementProgressBy(10);
		}
		
		public void onPostExecute(Boolean result){
			
			super.onPostExecute(result);
			
			//dialog.dismiss();
			if(!result){
				Toast.makeText(this.context, "Failed to log in", Toast.LENGTH_LONG).show();
				
				if(this.context instanceof Activity){
					((Activity) this.context).showDialog(Constants.LOGIN_DIALOG);
					
				}
				
			}

	        if (dialog.isShowing()) {
	            dialog.dismiss();
	        }
	        
	        WebHelper.this.dbHelper.setUsername(username);
	        
	        if(this.context instanceof LoginActivity){
	        	((LoginActivity) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof ViewSavingsActivity){
	        	((ViewSavingsActivity) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof MainActivity){
	        	((MainActivity) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof TabRoot){
	        	//Log.e("web helper", "calling on auth in Tab Root");
	        	((TabRoot) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof AddMoneyActivity){
	        	((AddMoneyActivity) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof SetupAccountActivity){
	        	((SetupAccountActivity) this.context).onAuthenticate(this.username, result);
	        }
	        
	        if(this.context instanceof LinkExistingAccountActivity){
	        	((LinkExistingAccountActivity) this.context).onAuthenticate(this.username, result);
	        }
			
		}

	}
	
public class logoutTask extends AsyncTask<String, Integer, Boolean> {

		
		
		Context context;
		
		String username;
		
		logoutTask(Context context){
			
			this.context = context;
			
			username = null;
		}
		
		@Override
        protected void onPreExecute() {
			super.onPreExecute();

			
            
            
        }
		
		@Override
		protected Boolean doInBackground(String... params) {
			
	        
	        HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/logout.php");
		    
		    // Create local HTTP context
		    httpContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    


	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost, httpContext);
				
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

	        

	        return false;

		}
		

		
		public void onPostExecute(Boolean result){
			
			super.onPostExecute(result);
			



			
		}


	}

	/**
	 * registers the user using async task. 
	 * @author merrickc
	 *
	 */
	public class registerUserTask extends AsyncTask<String, String[], JSONObject> {

		ProgressDialog dialog;
		
		Context context;
		
		registerUserTask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
		}
		
		@Override
        protected void onPreExecute() {
            dialog.setTitle("Registering User...");
            dialog.show();
        }
		
		@Override
		protected JSONObject doInBackground(String... params) {
			String username = params[0];
			String password = params[1];
			String email = params[2];

			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/register.php");
		    
		    
		    // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("username", username));
	        nameValuePairs.add(new BasicNameValuePair("password", password));
	        nameValuePairs.add(new BasicNameValuePair("email", email));
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost);
				String result = EntityUtils.toString(response.getEntity());

				
				String status = "";
				JSONObject json = null;
				
				try {
					json = new JSONObject(result);
					status = json.getString("status");
				} catch (JSONException e1) {
					
					e1.printStackTrace();
				}
				
				
				
				/** if true, log in user **/
				if(status.equals("success")){
					
					nameValuePairs = new ArrayList<NameValuePair>();
			        nameValuePairs.add(new BasicNameValuePair("username", username));
			        nameValuePairs.add(new BasicNameValuePair("password",password));
			        nameValuePairs.add(new BasicNameValuePair("rememberMe", "0"));
			        
			        
			        
			        httpclient = new DefaultHttpClient();
				    httppost = new HttpPost(DPSSERVER + "/login.php");
				    
				    // Create local HTTP context
				    httpContext = new BasicHttpContext();
				    // Bind custom cookie store to the local context
				    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
				    
			        try {
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

			        // Execute HTTP Post Request
			        try {
						response = httpclient.execute(httppost, httpContext);
						result = EntityUtils.toString(response.getEntity());

						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(result);
							result = jsonObject.getString("status");

							
							if(result.equals("success")) {
								
								//WebHelper.this.getAccountInfo();
								WebHelper.this.dbHelper.setUsername(username);
								
								return jsonObject;
							}
							
						} catch (JSONException e) {
							
							e.printStackTrace();
						}
						
						
						
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					
					return json;
				}
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}


			return null;
		}
		
		@Override
		protected void onPostExecute(JSONObject json){
			
			if(json == null){
				Toast.makeText(context, "Could not register user. Check your internet connection", Toast.LENGTH_LONG).show();
			}
			
			String status = "";
			String message = "";
			
			
			try {
				status = json.getString("status");
			} catch (JSONException e) {
				//e.printStackTrace();
			}
			
			try {
				message = json.getString("message");
			} catch (JSONException e) {

			}

			dialog.dismiss();
			
			
			if(status.equals("fail")){
				WebHelper.this.errorMessage = message;
				if(WebHelper.this.activity instanceof Activity)
					((Activity) WebHelper.this.activity).showDialog(Constants.ERROR_DIALOG);
				
			}
			else{
				
				if(this.context instanceof SetupAccountActivity){
					((SetupAccountActivity) this.context).onRegisterUser();
				}
				
				
			}
			
			
		}



	}
	
	/**
	 * registers the user using async task. 
	 * @author merrickc
	 *
	 */
	public class registerYodleeUserTask extends AsyncTask<String, String[], JSONObject> {

		ProgressDialog dialog;
		
		Context context;
		
		registerYodleeUserTask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
		}
		
		@Override
        protected void onPreExecute() {
            dialog.setTitle("Registering User...");
            dialog.show();
        }
		
		@Override
		protected JSONObject doInBackground(String... params) {
			
			JSONObject jsonResponse = null;
			
			
			String username = params[0];
			String password = Utility.md5(params[1]);

			String email = params[2];

			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/registerYodlee.php");
		    
		    
		    // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("username", username));
	        nameValuePairs.add(new BasicNameValuePair("password", password));
	        nameValuePairs.add(new BasicNameValuePair("email", email));
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
				HttpResponse response = httpclient.execute(httppost);
				String result = EntityUtils.toString(response.getEntity());
				Log.e("WEB RESPONSE", result);
				
				
				String status = "";
				try {
					jsonResponse = new JSONObject(result);
					status = jsonResponse.getString("status");
				} catch (JSONException e1) {
					
					e1.printStackTrace();
				}
				
				/** if true, log in user **/
				if(status.equalsIgnoreCase("success")){
					
					nameValuePairs = new ArrayList<NameValuePair>();
			        nameValuePairs.add(new BasicNameValuePair("username", username));
			        nameValuePairs.add(new BasicNameValuePair("password",password));
			        nameValuePairs.add(new BasicNameValuePair("rememberMe", "0"));
			        
			        
			        
			        httpclient = new DefaultHttpClient();
				    httppost = new HttpPost(DPSSERVER + "/login.php");
				    
				    // Create local HTTP context
				    httpContext = new BasicHttpContext();
				    // Bind custom cookie store to the local context
				    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
				    
			        try {
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

			        // Execute HTTP Post Request
			        try {
						response = httpclient.execute(httppost, httpContext);
						result = EntityUtils.toString(response.getEntity());
	
						
						try {
							jsonResponse = new JSONObject(result);
							result = jsonResponse.getString("status");

							
							if(result.equals("success")) {
								
								//WebHelper.this.getAccountInfo();
								WebHelper.this.dbHelper.setUsername(username);

								
								
							}
							
							return jsonResponse;
							
							
						} catch (JSONException e) {
							
							e.printStackTrace();
						}
						
						
						
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					
					return jsonResponse;
				}
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}


			return jsonResponse;
		}
		
		@Override
		protected void onPostExecute(JSONObject json){
			
			
			if(dialog.isShowing()) dialog.dismiss();
			
			if(json == null){
				return;
			}
			
			String status = null;
			String message = null;
			try {
				
				status = json.getString("status");
				
				message = json.getString("message");
				
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			if(status == null) return;
			
			
			if(status.equals("fail")){
				Toast.makeText(context, message, Toast.LENGTH_LONG).show();
			}
			else{

				
				
				if(context instanceof LinkExistingAccountActivity){
					//success, so return TRUE to onRegisterYodlee
					((LinkExistingAccountActivity) context).onRegisterYodleeUser(true);
				}
			}
			
			
		}



	}

	/**
	 * calls async thread to check if username is available. stores result in "onPostExecuteResult"
	 * @author merrickc
	 *
	 */
	public class checkUsernameTask extends AsyncTask<String, Integer, Boolean>{

		ProgressDialog dialog;
		
		Context context;
		
		checkUsernameTask(Context context){
			
			this.context = context;
			dialog = new ProgressDialog(context);
		}
		
		@Override
        protected void onPreExecute() {
            dialog.setTitle("Checking Username...");
            //dialog.show();
        }
		
		@Override
		protected Boolean doInBackground(String... params) {
			
			String username = params[0];
			

	    	
	    	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("username", username));
	        
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(DPSSERVER + "/checkUserExists.php");
		    
		    // Create local HTTP context
		    HttpContext localContext = new BasicHttpContext();
		    // Bind custom cookie store to the local context
		    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		    
		    boolean usernameAvailable = false;
		    
		    try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

	        // Execute HTTP Post Request
	        try {
	        	
	        	//Log.e(tag, "EXECUTING HTTPPOST");
				HttpResponse response = httpclient.execute(httppost, localContext);
				String result = EntityUtils.toString(response.getEntity());


				
				/** if server returns 0 accounts with that name **/
				if(Integer.parseInt(result) < 1){
					usernameAvailable = true;
				}
				else{
					usernameAvailable = false;
				}
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NumberFormatException e){
				usernameAvailable = false;
			}

	        
	        
	        return usernameAvailable;

		}
		
		@Override
		public void onPostExecute(Boolean result){
			dialog.dismiss();
		}
		
		
	}
	
	
	/**
	 * calls new thread to register user. 
	 * @param username
	 * @param password
	 * @param email
	 * @return true if success. gets result in "onPostExecuteResult" which is set by the thread
	 */
	public Boolean registerUser(String username, String password, String email){
		
		String encryptedPassword = Utility.md5(password);
		
		try {
			new registerUserTask(this.activity).execute(username, encryptedPassword, email).get();
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		
		return true;
			
	}
	
	public Boolean registerYodleeUser(String username, String password, String email){
		
		//String encryptedPassword = Utility.md5(password);
		
		
			new registerYodleeUserTask(this.activity).execute(username, password, email);
			

		
		return false;
	}
	
	/**
	 * submit account info to server. 
	 * given content values, containing account data
	 * @return
	 */
	public boolean registerAccount(ContentValues values){
		
		/** extract each of the values and put into POST **/
	    String accountName = values.getAsString(AccountDBHelper.COLUMN_ACCOUNT_NAME);
	    String checkingNum = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_CHECKNUM);
	    String routeNum = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_ROUTENUM);
	    
	    String firstName = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_FIRSTNAME);
	    String lastName = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_LASTNAME);
	    String birthdate = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_BIRTHDATE);
	    String socialSecurity = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_SOCIAL_SECURITY);
	    
	    String phoneNumber = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_PHONE_NUMBER);
	    String homeAddress = (String) values.get(AccountDBHelper.COLUMN_ACCOUNT_HOME_ADDRESS);
	    String homeCity = values.getAsString(AccountDBHelper.COLUMN_ACCOUNT_HOME_CITY);
	    String homeState = values.getAsString(AccountDBHelper.COLUMN_ACCOUNT_HOME_CITY);
	    String homeZip = values.getAsString(AccountDBHelper.COLUMN_ACCOUNT_HOME_ZIP);
	    
	    JSONObject object = new JSONObject();
	    
	    try {
	    	object.put("name", accountName);
	    	object.put("checkingNum", checkingNum);
	    	object.put("routeNum", routeNum);
	    	
	    	object.put("firstName", firstName);
	    	object.put("lastName", lastName);
	    	
	    	object.put("birthdate", birthdate);
	    	object.put("socialSecurity", socialSecurity);
	    	
	    	object.put("phoneNumber", phoneNumber);
	    	object.put("homeAddress", homeAddress);
	    	object.put("homeCity", homeCity);
	    	object.put("homeState", homeState);
	    	object.put("homeZip", homeZip);
	    	
	    	//object.put("ownerID", this.dbHelper.getUserID())
	    	
	    	
	    }
	    catch(JSONException e){
	    	e.printStackTrace();
	    }
	    
        
        try {

			if(new createAccountTask().execute(object).get() == true){
				
				this.getAccountInfo(true);
				this.dbHelper.setBoolean(DBHelper.COLUMN_ACCOUNT_CREATED, 1);
				return true;
			}
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * calls new thread to check username availability. 
	 * @param username
	 * @return 
	 * @return if success, returns true; grabs result from onPostExecute variable, which is set by the thead in "onPostExecute"
	 */
	public Boolean checkUsernameAvailable(String username) {
		try {
			return new checkUsernameTask(activity).execute(username).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * calls new thread to log user in. 
	 * @param username
	 * @param password
	 * @return true/false if success/failed. thread sets result of action to "postExecuteResult" variable;
	 */
	public void login(String username, String password, boolean rememberMe){
		
		String rememberUser = "0";
		if(rememberMe) rememberUser = "1";

		new loginTask(this.activity).execute(username, password, rememberUser);
				
        //return false;
		

	}
	
	public void logout(){
		
		this.cookieStore.clear();
		
		//if remember me, keep username
		//if(!this.dbHelper.getBoolean(DBHelper.COLUMN_REMEMBER_ME))
			this.dbHelper.setUsername("");
		
		this.accountDBHelper.deleteAll();
		
		
		new logoutTask(activity).execute();
		
		Toast.makeText(this.activity, "Logged Out", Toast.LENGTH_LONG).show();
		

	}

	
	
	/** checks if the user has internet **/
	public boolean hasConnection() {
	    ConnectivityManager cm =
	        (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
	
	/**
	 * handles authentication for the user. user must be authenticated to interact with web server and add/view savings
	 */
	public boolean authenticate(String returnTab){

		/** check for session cookie **/
		//Cookie cookie;
		cookieStore.clearExpired(new Date());
		
		String username = this.dbHelper.getUsername();
		
		if(username != null){
			
			try {
				if(new checkSessionTask(this.activity).execute(username).get() == true){

					return true;
				}
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}

		}
		
		
		
		
			
		/** no session cookie, request login **/
		Intent intent = new Intent(this.activity, LoginActivity.class);
		
		
		intent.putExtra("START_TAB", returnTab);
		this.activity.startActivity(intent);
		
		return false;
		

	}
	
	
	public void checkSession(){
		
		new checkSessionTask(this.activity).execute(this.dbHelper.getUsername());
		
	}
	
	
	
	
	/**
	 * get account info for user id
	 * @param userid
	 * @return
	 */
	public void getAccountInfo(boolean showDialog){
		
		int userid = this.dbHelper.getUserID();
		

		new getAccountInfoTask(this.activity, showDialog).execute(userid);


	}
	
	public void addExistingAccountInfo(String bank, String bankUsername, String bankPass, boolean showDialog){
		
		int userid = this.dbHelper.getUserID();
		
		JSONObject json = new JSONObject();
		
		/** don't allow null values **/
		if(bank == null || bankUsername == null || bankPass == null) return;
		
		try {
			int contentServiceID;
			try{
				contentServiceID = (Integer) bankMap.get(bank);
			}
			catch(NullPointerException e){
				e.printStackTrace();
				return;
			}
			
			json.put("contentServiceID", contentServiceID);
			json.put("bankName", bankUsername);
			json.put("bankPass", bankPass);
			

		} catch (JSONException e) {
			e.printStackTrace();
		}

		new addExistingAccountInfoTask(this.activity, showDialog).execute(json);


	}
	
	public void getExistingAccountInfo(String bank, String bankUsername, String bankPass, String yodleeName, String yodleePass, boolean showDialog){
		
		JSONObject json = new JSONObject();
		
		/** don't allow null values **/
		if(bank == null || bankUsername == null || bankPass == null) return;
		
		try {
			json.put("bank", bank);
			json.put("bankName", bankUsername);
			json.put("bankPass", bankPass);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		new getExistingAccountInfoTask(this.activity, showDialog).execute(json);


	}
	
	public void getExistingAccountInfo(boolean showDialog){
		
		new getExistingAccountInfoTask(this.activity, showDialog).execute();


	}

	
	
	public void updateAccountInfo(){
		
		this.authenticate("settings");
		
		JSONObject json = new JSONObject();
		
		Cursor accountsCursor = this.accountDBHelper.getAccountsAsCursor();
		
		
		for(int i = 0; i < accountsCursor.getCount(); i++){
			
			accountsCursor.moveToPosition(i);
			
			try{
				json.put("id", accountsCursor.getInt(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_ID)));
				
				//json.put("name", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_NAME)));
				json.put("checkNum", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_CHECKNUM)));
				json.put("routeNum", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_ROUTENUM)));
				json.put("amount", accountsCursor.getInt(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_AMOUNT)));
				
				json.put("firstName", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_FIRSTNAME)));
				json.put("lastName", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_LASTNAME)));
				
				
				json.put("birthdate", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_BIRTHDATE)));
				json.put("socialSecurity", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_SOCIAL_SECURITY)));
				json.put("phoneNumber", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_PHONE_NUMBER)));
				
				json.put("homeAddress", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_HOME_ADDRESS)));
				json.put("homeState", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_HOME_STATE)));
				json.put("homeCity", accountsCursor.getString(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_HOME_CITY)));
				json.put("homeZip", accountsCursor.getInt(accountsCursor.getColumnIndex(this.accountDBHelper.COLUMN_ACCOUNT_HOME_ZIP)));
				
				
			}
			catch(JSONException e){
				e.printStackTrace();
			}
			
			
			
			try {
				if(new updateAccountInfoTask(this.activity).execute(json).get() == false){
					//Toast.makeText(this.activity, "Failed to update Account Info", Toast.LENGTH_LONG).show();
				}
				else{
					
				}
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			
			
		}

		
	}
	
	public boolean updateUserInfo(){
		
		JSONObject json = new JSONObject();
		
		int achConfirmed = 0;
		if(this.dbHelper.getBoolean(DBHelper.COLUMN_ACH_CONFIRMED)) achConfirmed = 1;
		
		
		try {
			json.put("username", this.dbHelper.getUsername());
			json.put("password", this.dbHelper.getColumnString(DBHelper.COLUMN_PASSWORD));
			json.put("achConfirmed", achConfirmed);
			json.put("mode", this.dbHelper.getMode());
			json.put("email", this.dbHelper.getColumnString(DBHelper.COLUMN_EMAIL));
			
			//json.put("password", this.dbHelper.getPassword());
			
			
			
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
		try {
			return new updateUserInfoTask().execute(json).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			
			e.printStackTrace();
		}
		
		return false;
		
	}

	public boolean isLoggedIn() {
		
		/** check for session cookie **/
		//Cookie cookie;
		cookieStore.clearExpired(new Date());
		
		String username = this.dbHelper.getUsername();
		
		if(username == null || username.equals("")){
			return false;
		}
		
		if(cookieStore.getCookies() != null){
			
			for(Cookie cookie : cookieStore.getCookies()){
				
				
				if(cookie.getDomain().equals(DOMAIN)){

					return true;
				}
			}
		}
		else{
			return false;
		}
		

		
		return true;
		
		
	}

	/**
	 * adds teh transfer to onlinen DB and performs money switch between accounts
	 * @param from
	 * @param to
	 * @param amount
	 * @return
	 */
	public boolean performTransfer(String from, String to, int amount) {
		
	
		
		//connect online to add transfers and check if able
		Account fromAccount = accountDBHelper.getAccountAsAccount(from);
		Account toAccount = accountDBHelper.getAccountAsAccount(to);
		
		
		int fromID = fromAccount.id;
		int toID = toAccount.id;
		/** TODO ids = 0 ^^^^ **/
		
		
		new performTransferTask(this.activity).execute(fromID, toID, amount);
		
		return true;

	}
	
	public void getTransfers(){
		
		new getTransfersTask(this.activity).execute();
		
		
	}
	
	
	public void answerMFA(JSONObject json){
		new AnswerMFATask(this.activity).execute(json);
	}

	public void getUserInfo() {
		
		new getUserInfoTask(this.activity, false).execute();
		
	}


	public void unlinkYodleeAccount() {
		
		class unlinkYodleeAccountTask extends AsyncTask<String, Integer, Boolean> {
			
			//ProgressDialog dialog;
			
			@Override
			protected void onPreExecute(){

			}

			@Override
			protected Boolean doInBackground(String... arg0) {
				HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/removeUserItems.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);


		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());
					Log.e("WEB RESPONSE", result);
					JSONObject jsonObject = null;
					try {
						jsonObject = new JSONObject(result);
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
					//jsonObject.
					try {
						result = jsonObject.getString("status");
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
					if(result.equals("success")) return true;
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

		        

		        return false;
			}
			
			@Override
			protected void onPostExecute(Boolean result){

				
				if(result == true){
					WebHelper.this.dbHelper.setMode(0);
					WebHelper.this.accountDBHelper.deleteAccounts();
					Toast.makeText(WebHelper.this.activity, "Successfully removed account", Toast.LENGTH_LONG).show();
					return;
				}
				else{
					Toast.makeText(WebHelper.this.activity, "Unable to remove account. Try again later.", Toast.LENGTH_LONG).show();
					return;
				}
				
			}
			
		}
		
		
		new unlinkYodleeAccountTask().execute();
			
		
		
	}
	

	
	public void confirmACH(double depositAmount, double withdrawalAmount) {
		
		class ConfirmACHTask extends AsyncTask<Double, Integer, JSONObject> {
			
			ProgressDialog dialog;
			
			@Override
			protected void onPreExecute(){
				dialog = new ProgressDialog(WebHelper.this.activity);
				
				dialog.show();
			}

			@Override
			protected JSONObject doInBackground(Double...amounts) {
				
				double deposit = amounts[0];
				double withdrawal = amounts[1];
				
				HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "confirmACH.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    
			    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		        nameValuePairs.add(new BasicNameValuePair("deposit", String.valueOf(deposit)));
		        nameValuePairs.add(new BasicNameValuePair("withdrawal", String.valueOf(withdrawal)));
		        
		        try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}


		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

					JSONObject jsonObject = null;
					try {
						jsonObject = new JSONObject(result);
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
					//jsonObject.
					try {
						result = jsonObject.getString("status");
						//Log.e(tag, result);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
					return jsonObject;
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

		        

		        return null;
			}
			
			@Override
			protected void onPostExecute(JSONObject json){
				
				/** SET ACH Confimed to true, restart addMOney **/
				
				
				if(dialog != null) dialog.dismiss();
				
				String status = "";
				String message = "";
				
				try {
					status = json.getString("status");
					message = json.getString("message");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				if(status.equalsIgnoreCase("success")){
					
					Toast.makeText(WebHelper.this.activity, "ACH Confirmed", Toast.LENGTH_LONG).show();
					
					WebHelper.this.getUserInfo();
					
					WebHelper.this.dbHelper.setBoolean(DBHelper.COLUMN_ACH_CONFIRMED, 1);
					
					Intent intent = new Intent(WebHelper.this.activity, TabRoot.class);
					intent.putExtra("START_TAB", "add_money");
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					
					WebHelper.this.activity.startActivity(intent);
					
					
					return;
				}
				else{
					if(message.equalsIgnoreCase("must be logged in"))
						Toast.makeText(WebHelper.this.activity, "You must log in to confirm your ACH deposit", Toast.LENGTH_LONG).show();
					else
						Toast.makeText(WebHelper.this.activity, "Failed to confirm ACH deposit/withdrawal", Toast.LENGTH_LONG).show();
					
					
					return;
				}
				
			}
			
		}
		
		
		new ConfirmACHTask().execute(depositAmount, withdrawalAmount);
			
		
		
	}


	
	public void updateExistingAccountInfo(String bank, String bankUsername, String bankPass, boolean showDialog){

		
		/** updates a bank account to a yodlee ID **/
		class updateExistingAccountInfoTask extends AsyncTask<JSONObject, String, JSONObject>{


			DBHelper dbHelper;
			
			AccountDBHelper accountDBHelper;
			
			ProgressDialog dialog;
			
			Context context;
			
			boolean showDialog;
			
			updateExistingAccountInfoTask(Context context, boolean showDialog){

				
				this.context = context;
				dialog = new ProgressDialog(context);
				
				this.showDialog = showDialog;
				
				this.accountDBHelper = new AccountDBHelper(context);
				this.dbHelper = new DBHelper(context);
			}
			
			
			
			@Override
	        protected void onPreExecute() {
				super.onPreExecute();

				
				if(showDialog){
					dialog = ProgressDialog.show(context,
			                "", "Updating Account Information");
				}
				
				
			}
			@Override
			protected JSONObject doInBackground(JSONObject... json) {
				
				
				HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost(DPSSERVER + "../yodlee/removeUserItems.php");
			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);


			    
		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());
					JSONObject jsonObject = null;
					try {
						jsonObject = new JSONObject(result);
					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
					//jsonObject.
					try {
						result = jsonObject.getString("status");

					} catch (JSONException e) {
						
						e.printStackTrace();
					}
					
				
					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		        
		        
		
				httpclient = new DefaultHttpClient();
			    httppost = new HttpPost(DPSSERVER + "../yodlee/addYodleeAccount.php");
			    

			    //if arguments are not null, add the json bank info 
			    if(json[0] != null){
			    	List<NameValuePair> values = new ArrayList<NameValuePair>();
			        values.add(new BasicNameValuePair("json", json[0].toString()));
			        
			        try {
						httppost.setEntity(new UrlEncodedFormEntity(values));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
			    }

			    
			    // Create local HTTP context
			    httpContext = new BasicHttpContext();
			    // Bind custom cookie store to the local context
			    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			    

		        // Execute HTTP Post Request
		        try {
					HttpResponse response = httpclient.execute(httppost, httpContext);
					String result = EntityUtils.toString(response.getEntity());

					Log.e("Update Yodlee Response", result);
					
					try {
						JSONObject jsonResponse = new JSONObject(result);
						return jsonResponse;
					} catch (JSONException e) {
						
						e.printStackTrace();
						return null;
					}

					
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				return null;

			}
			
			
			@Override
			public void onPostExecute(JSONObject json){
				
				super.onPostExecute(json);
				
				if(json == null){
					if (dialog.isShowing()) {
			            dialog.dismiss();
			        }
					return;
				}
				String status = null;
				String message = null;
				
				try {
					status = json.getString("status");
					
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				
				
				//if(status.equalsIgnoreCase("success"))
				if(activity instanceof ViewSavingsActivity){
					//((ViewSavingsActivity) activity).onGetExistingAccountInfo(acount);

				}
				
				if(activity instanceof AddMoneyActivity){
					//((AddMoneyActivity) activity).onGetAccountInfo(accounts);

				}
				if(activity instanceof LinkExistingAccountActivity){
					((LinkExistingAccountActivity)activity).onAddExistingAccountInfo(json);
					
				}
				
				

				try{
			        if (dialog.isShowing()) {
			            dialog.dismiss();
			        }
				}
				catch(Exception e){
					//nothing to do here;
				}

				
			}

		}


		JSONObject json = new JSONObject();
		
		/** don't allow null values **/
		if(bank == null || bankUsername == null || bankPass == null){
			
			return;
		}
		
		try {

			int contentServiceID;
			try{
				contentServiceID = (Integer) bankMap.get(bank);
			}
			catch(NullPointerException e){
				return;
			}
			
			json.put("contentServiceID", contentServiceID);
			json.put("bankName", bankUsername);
			json.put("bankPass", bankPass);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		
		new updateExistingAccountInfoTask(this.activity, true).execute(json);

		
	}


	public void uploadImage(String string) {
		class uploadImageTask extends AsyncTask<String, String, Boolean>{

			@Override
			protected Boolean doInBackground(String... filePath) {
				
				
				Bitmap bitmap = BitmapFactory.decodeFile(filePath[0]);
		    	ByteArrayOutputStream stream = new ByteArrayOutputStream();

		    	
		    	if(bitmap == null){
		    		return false;
		    	}
		    	
		        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
		        byte [] byte_arr = stream.toByteArray();
		        String image_str = Base64.encodeToString(byte_arr, 0);
		        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

		        nameValuePairs.add(new BasicNameValuePair("image",image_str));

		        try{
		            HttpClient httpclient = new DefaultHttpClient();
		            HttpPost httppost = new HttpPost("https://www.downpaymentsaver.com/downpaymentserver/licenseUpload.php");
		            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		            HttpResponse response = httpclient.execute(httppost);
		            String the_string_response = response.getEntity().toString();
		            
		            
		            
		        }catch(Exception e){
		        	
		        }
				
				
				return true;
				
				
				
			}
			
			
			
		}
		
		
		new uploadImageTask().execute(string);
		
		
		
		
	}
	
	public void uploadLicense(String location, String side) {
		class uploadLicenseTask extends AsyncTask<String, String, String>{
			
			
			public void uploadLicense(String pathName, String side){
		    	Bitmap bitmap = Utility.decodeSampledBitmapFromFile(pathName.replace("file://", ""), 500, 500);
		    	ByteArrayOutputStream stream = new ByteArrayOutputStream();


		    	if(bitmap == null){
		    		return;
		    	}
		    	
		        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); //compress to which format you want.
		        byte [] byte_arr = stream.toByteArray();
		        String image_str = Base64.encodeToString(byte_arr, 0);
		        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

		        nameValuePairs.add(new BasicNameValuePair("image",image_str));
		        nameValuePairs.add(new BasicNameValuePair("side", side));

		        try{
		        	
				    httpContext = new BasicHttpContext();
				    // Bind custom cookie store to the local context
				    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
				    
		            HttpClient httpclient = new DefaultHttpClient();
		            HttpPost httppost = new HttpPost("https://www.downpaymentsaver.com/downpaymentserver/licenseUpload.php");
		            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		            HttpResponse response = httpclient.execute(httppost, httpContext);
		            String result = EntityUtils.toString(response.getEntity());
		            
		            		            
		        }catch(Exception e){
		        }
		        
			}

			@Override
			protected String doInBackground(String... args) {
				
				
				uploadLicense(args[0], args[1]);
				
				
				//return the URI to delete on Post Execute
				return args[0];
				
				
				
			}
			
			@Override
			protected void  onPostExecute(String imagePath){
				File file = new File(imagePath);
				boolean deleted = file.delete();
				
				
			}
			
			
			
		}
		
		
		
		new uploadLicenseTask().execute(location, side);
		
		
		
		
	}

    	
	
}

